var run_on_gadget = 0;
var obs;

function initApiCall() {

    if (typeof (gadgets.window) != "undefined") {
        run_on_gadget = 1;
    } 

    obs = new Observable();
    Task.setEventListener(obs);

    $("#datepicker").datepicker().hide().click(function (evt) {
        evt.stopPropagation();
        $(this).hide();
    });
    $("datepicker").keyup(function(e) {
        if(e.keyCode == 27) { $(this).hide(); }
    });

    if (run_on_gadget) {
        google.calendar.subscribeToDates(timerTasks);
    } else {
        var dates = {};
        dates.startTime = new Date(2014, 3, 1);
        dates.endTime = new Date();

        timerTasks(dates);
    }
}

function timerTasks(dates) {
    if (timer) {
        console.log("clean : " + timer);
        clearTimeout(timer);
    }
    request_tasklist(dates);
    if (run_on_gadget) {
        timer = setTimeout(function (dates) {
            var token = gapi.auth.getToken();
            var now = Math.floor(Date.now() / 1000);
            if (token.expires_at < now) {
                console.log("Token reget");
                window.setTimeout(checkAuth, 1);
            } else {
                timerTasks(dates);
            }
        }, 60 * 1000, dates);
        console.log("set : " + timer);
    }
}

function request_tasklist(dates) {

    var mylist = document.getElementById("mylist");
    mylist.innerHTML = "";

    gapi.client.load('tasks', 'v1', function () {
        var request = gapi.client.tasks.tasklists.list({
            'userId': 'me'
        });

        request.execute(function (resp) {
            if (resp.code && resp.code != 200) {
                console.log(resp);
            }

            if (resp.items) {
                resp.items.forEach(function (val, index, theArray) {
                    var tasklist = new Tasklist(val);
                    mylist.appendChild(tasklist.elem);

                    tasklist.request_list(dates);
                });
            }
        });
    });
}

